<template>
    <el-container>
        <el-aside width="120px" class="aside">
            <el-button size="small" type="primary" plain @click="onAddGuicklinkGroup"
                style="width: 100%;">新增</el-button>
            <el-anchor :container="containerRef" :offset="70" direction="vertical" type="default"
                @change="handleAnchorChange">
                <el-anchor-link v-for="anchor in quicklinkGroups" :key="anchor.id" :href="'#part' + anchor.id"
                    @contextmenu="onQuicklinkGroupContextMenu(anchor, $event)">
                    <span>{{ anchor.name }}</span>
                </el-anchor-link>
            </el-anchor>
        </el-aside>
        <el-main style="padding: 0px 10px;">
            <div ref="containerRef" style="height: 100%;overflow-y: auto;overflow-x: hidden;">
                <div v-for="anchor in quicklinkGroups" :key="anchor.id" :id="'part' + anchor.id"
                    style="background-color: #FFFFFF;">
                    <div style="padding: 10px;display: inline-flex;align-items: center;">
                        <KuiIcon name="Operation" />
                        <span style="margin: 0 5px;">{{ anchor.name }}</span>
                    </div>
                    <el-row :gutter="20" style="color: #303133;padding: 10px;">
                        <el-col :span="4" v-for="tool in anchor.tools" :key="tool.id">
                            <div class="quicklink-item" @click="openQuicklink(tool)"
                                @contextmenu="onQuickLinkContextMenu(tool, $event)">
                                <img :src="faviconUrl(tool.url)" style="width: 20px;height: 20px;margin-right: 5px;" />
                                {{ tool.name }}
                            </div>
                        </el-col>
                        <el-col :span="4" style="cursor: pointer;" @click="onAddquicklink(anchor.id)">
                            <div class="quicklink-item" style="text-align: center;">
                                <KuiIcon name="Plus" />
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>

        </el-main>
        <el-dialog title="新增工具" v-model="quicklinkModal.visible">
            <el-form :model="quicklinkModal.quicklink">
                <el-form-item label="名称">
                    <el-input v-model="quicklinkModal.quicklink.name"></el-input>
                </el-form-item>
                <el-form-item label="图标">
                    <el-input v-model="quicklinkModal.quicklink.icon"></el-input>
                </el-form-item>
                <el-form-item label="链接">
                    <el-input v-model="quicklinkModal.quicklink.url"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="quicklinkModal.visible = false">取消</el-button>
                    <el-button type="primary" @click="savequicklink">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </el-container>
</template>
<script>
import { ElMessageBox } from 'element-plus'
import { cloneDeep } from 'lodash';
import { ref } from 'vue';
export default {
    setup() {
        const containerRef = ref(null);
        return {
            containerRef,
        };
    },
    data() {
        return {
            quicklinkGroups: [],

            quicklinkModal: {
                visible: false,
                quicklink: {
                    id: '',
                    groupId: '',
                    name: '',
                    icon: '',
                    url: '',
                },
            },
        }
    },
    mounted() {
        this.getquicklinkGroups();
    },
    methods: {
        getquicklinkGroups() {
            this.$api.quicklink.listGroupsWithLinks().then(resp => {
                this.quicklinkGroups = resp.data;
                // console.log(resp.data);
            });
        },
        onAddGuicklinkGroup() {
            ElMessageBox.prompt('输入工具组名称', '新增工具组', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                this.$api.quicklink.addGroup({ name: value }).then(res => {
                    this.quicklinkGroups.push({
                        id: res.data.id,
                        name: value,
                        tools: [],
                    });
                });
            })
        },
        onUpdatequicklinkGroup(group) {
            ElMessageBox.prompt('输入工具组名称', '新增工具组', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                inputValue: group.name,
            }).then(({ value }) => {
                this.$api.quicklink.updateGroup({ id: group.id, name: value }).then(res => {
                    this.quicklinkGroups.forEach((group) => {
                        if (group.id === res.data.id) {
                            group.name = value;
                        }
                    })
                });
            })
        },
        onDeletequicklinkGroup(group) {
            ElMessageBox.confirm('确定要删除该工具组吗？', '删除工具组', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.$api.quicklink.deleteGroupWithLinks(group.id).then(res => {
                    this.quicklinkGroups = this.quicklinkGroups.filter(item => item.id !== group.id)
                })
            })
        },
        onAddquicklink(groupId) {
            this.quicklinkModal.quicklink = {
                id: '',
                groupId: groupId,
                name: '',
                icon: '',
                url: '',
            };
            this.quicklinkModal.visible = true;
        },
        onUpdatequicklink(tool) {
            this.quicklinkModal.quicklink = cloneDeep(tool);
            this.quicklinkModal.visible = true;
        },
        onDeletequicklink(tool) {
            ElMessageBox.confirm('确定要删除该链接吗？', '删除链接', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.$api.quicklink.delete(tool.id).then(res => {
                    this.quicklinkGroups.forEach((group) => {
                        if (group.id === tool.groupId) {
                            group.tools = group.tools.filter(item => item.id !== tool.id)
                        }
                    })
                })
            })
        },
        savequicklink() {
            if (this.quicklinkModal.quicklink.id) {
                this.$api.quicklink.update(this.quicklinkModal.quicklink).then(res => {
                    this.quicklinkGroups.forEach((group) => {
                        group.tools.forEach((tool) => {
                            if (tool.id === res.data.id) {
                                tool.name = res.data.name;
                                tool.icon = res.data.icon;
                                tool.url = res.data.url;
                            }
                        });
                    })
                    this.quicklinkModal.visible = false;
                })
            } else {
                this.$api.quicklink.add(this.quicklinkModal.quicklink).then(res => {
                    this.quicklinkGroups.forEach(group => {
                        if (group.id === res.data.groupId) {
                            group.tools.push(res.data);
                        }
                    });
                    this.quicklinkModal.visible = false;
                });
            }
        },
        openQuicklink(tool) {
            window.open(tool.url, '_blank');
        },
        handleAnchorChange(anchor) {
            console.log(anchor);
        },
        onQuicklinkGroupContextMenu(group, e) {
            e.preventDefault();
            this.$contextmenu({
                theme: 'flat',
                preserveIconWidth: false,
                items: [
                    {
                        label: '编辑',
                        onClick: () => {
                            this.onUpdatequicklinkGroup(group);
                        },
                    },
                    {
                        label: '删除',
                        onClick: () => this.onDeletequicklinkGroup(group),
                    }
                ],
                zIndex: 3,
                minWidth: 120,
                x: e.x,
                y: e.y,
            });
        },
        onQuickLinkContextMenu(tool, e) {
            //prevent the browser's default menu
            e.preventDefault();
            //show our menu
            this.$contextmenu({
                theme: 'flat',
                preserveIconWidth: false,
                items: [
                    {
                        label: '编辑',
                        onClick: () => {
                            this.onUpdatequicklink(tool);
                        },
                    },
                    {
                        label: '删除',
                        onClick: () => this.onDeletequicklink(tool),
                    }
                ],
                zIndex: 3,
                minWidth: 120,
                x: e.x,
                y: e.y,
            });
        },
        faviconUrl(url) {
            //从URL地址解析出路径，去除参数
            // url = url.replace(/[?#].*$/, '');
            // // 考虑结尾/的场景
            // if(url.endsWith('/')){
            //     url = url.substring(0, url.length - 1);
            // }
            // 解析url中的域名信息
            const domain = url.match(/https?:\/\/([^/]+)/)[1];
            url = 'https://favicon.im/';
            // url = 'https://toolb.cn/favicon/';
            return `${url}/${domain}`;
        },
    },
}
</script>

<style lang="scss" scoped>
.aside {
    // background-color: aliceblue;
}

.quicklink-item {
    padding: 10px 20px;
    background-color: aliceblue;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-content: center;
    height: 20px;


}

:deep(.el-anchor__list) {
    .el-anchor__link {
        padding: 10px 10px;
        font-size: 15px;
    }
}
</style>